package com.epam.rentcar.controller.actions;

import java.io.UnsupportedEncodingException;
import java.sql.SQLException;

import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.epam.rentcar.DAO.DAOFactory;
import com.epam.rentcar.DAO.UserDAO;
import com.epam.rentcar.utils.dbconn.ConnectionFactory;

public class RegisterAction implements Action {

	private DAOFactory daoFactory = DAOFactory.getDAOFactory(DAOFactory.MySQL);
	private UserDAO userDAO = daoFactory.getUserDAO(ConnectionFactory.MySQL);
	
	private static Logger log = Logger.getLogger(RegisterAction.class);

	@Override
	public String perform(HttpServletRequest request,
			HttpServletResponse response) {

		String login = request.getParameter("login");
		String password = request.getParameter("password");

		try {
			login = new String(login.getBytes("ISO8859_1"), "UTF-8");
			password = new String(password.getBytes("ISO8859_1"), "UTF-8");

			if (userDAO.addUser(login, password)) {
				return "/main.jsp";
			} 
		} catch (SQLException | NamingException | UnsupportedEncodingException | NullPointerException e) {
			log.error(e);
		}
		
		request.setAttribute("message", "try to use another login");
		return "/message.jsp";
	}

}
